package com.qimu.saiyou.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.qimu.saiyou.common.BaseResponse;
import com.qimu.saiyou.common.ErrorCode;
import com.qimu.saiyou.common.ResultUtils;
import com.qimu.saiyou.exception.BusinessException;
import com.qimu.saiyou.manager.RedisLimiterManager;
import com.qimu.saiyou.model.dto.friendsapply.FriendsQueryRequest;
import com.qimu.saiyou.model.dto.friendsapply.UpdateFriendRemark;
import com.qimu.saiyou.model.entity.Friends;
import com.qimu.saiyou.model.entity.User;
import com.qimu.saiyou.model.vo.UserFriendDTO;
import com.qimu.saiyou.service.FriendsService;
import com.qimu.saiyou.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * 好友
 *
 *@author: FeiXiang
 * 
 */
@RestController
@RequestMapping("/friends")
@Slf4j
public class FriendsController {
    @Resource
    private FriendsService friendsService;
    @Resource
    private UserService userService;
    @Resource
    private RedisLimiterManager redisLimiterManager;

    // region 增删改查

    @PostMapping("/list/vo")
    public BaseResponse<Page<UserFriendDTO>> listMyFriendsByPage(@RequestBody FriendsQueryRequest friendsQueryRequest, HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        int current = friendsQueryRequest.getCurrent();
        int pageSize = friendsQueryRequest.getPageSize();
        String sortField = friendsQueryRequest.getSortField();
        String sortOrder = friendsQueryRequest.getSortOrder();
        String searchText = friendsQueryRequest.getSearchText();

        MPJLambdaWrapper<User> lambdaWrapper = new MPJLambdaWrapper<User>()
                .selectAll(User.class)
                .selectAs(User::getId, "userId")
                .selectAs(Friends::getId, "fId")
                .selectAll(Friends.class);
        if (StringUtils.isNotBlank(searchText)) {
            lambdaWrapper.and(w -> {
                w.like(User::getUserName, searchText);
                w.or();
                w.like(User::getUserAccount, searchText);
                w.or();
                w.like(Friends::getRemark, searchText);
            });
        }
        MPJLambdaWrapper<User> wrapper = lambdaWrapper
                .eq(Friends::getUserId, loginUser.getId())
                .leftJoin(Friends.class, Friends::getReceiveId, User::getId);
        Page<UserFriendDTO> userFriendDTOPage = userService.selectJoinListPage(new Page<>(current, pageSize), UserFriendDTO.class, wrapper);
        return ResultUtils.success(userFriendDTOPage);
    }

    @GetMapping("/id")
    public BaseResponse<UserFriendDTO> getUserFriendById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        Friends friends = friendsService.lambdaQuery()
                .eq(Friends::getReceiveId, id)
                .eq(Friends::getUserId, loginUser.getId())
                .one();
        if (friends == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "好友不存在");
        }
        if (!friends.getUserId().equals(loginUser.getId())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "无权限");
        }

        User user = userService.getById(friends.getReceiveId());
        UserFriendDTO userFriendDTO = new UserFriendDTO();
        BeanUtils.copyProperties(user, userFriendDTO);
        userFriendDTO.setUserId(user.getId());
        userFriendDTO.setRemark(friends.getRemark());
        userFriendDTO.setFId(friends.getId());
        return ResultUtils.success(userFriendDTO);
    }

    @PostMapping("/update/remark")
    public BaseResponse<Boolean> updateFriendRemark(@RequestBody UpdateFriendRemark updateFriendRemark, HttpServletRequest request) {
        if (ObjectUtils.anyNull(updateFriendRemark, updateFriendRemark.getId()) || updateFriendRemark.getId() < 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        Friends friends = friendsService.lambdaQuery()
                .eq(Friends::getReceiveId, updateFriendRemark.getId())
                .eq(Friends::getUserId, loginUser.getId())
                .one();
        if (friends == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "好友不存在");
        }
        if (!friends.getUserId().equals(loginUser.getId())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "无权限");
        }
        friends.setRemark(updateFriendRemark.getRemark());
        return ResultUtils.success(friendsService.updateById(friends));
    }

    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteFriend(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        // 我的好友
        Friends friends = friendsService.lambdaQuery()
                .eq(Friends::getReceiveId, id)
                .eq(Friends::getUserId, loginUser.getId())
                .one();
        if (friends == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "好友不存在");
        }
        if (!friends.getUserId().equals(loginUser.getId())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "对方不是你的好友！");
        }
        // 对方的我
        Friends friends2 = friendsService.lambdaQuery()
                .eq(Friends::getReceiveId, loginUser.getId())
                .eq(Friends::getUserId, id)
                .one();
        if (friends2 == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "好友不存在");
        }
        if (!friends2.getReceiveId().equals(loginUser.getId())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "你不是对方的好友");
        }
        boolean removeBatchByIds = friendsService.removeBatchByIds(Arrays.asList(friends, friends2));
        return ResultUtils.success(removeBatchByIds);
    }
}
